<template>
  <div id="long-content-to-pdf">
    <h1>长页面内容导出为PDF</h1>
    <div v-for="n in 100" :key="n" class="section">
      <h2>Section{{ n }}</h2>
      <p>这是第{{ n }}段落的内容。</p>
    </div>
    <button @click="generatePDF">导出为PDF</button>
  </div>
</template>
<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  methods: {
    async generatePDF() {
      const element = document.getElementById('long-content-to-pdf');
      const sections = element.querySelectorAll('.section');
      const pdf = new jsPDF();

      for (let i = 0; i < sections.length; i++) {
        const section = sections[i];
        const canvas = await html2canvas(section, { scale: 2 });
        const imgData = canvas.toDataURL('image/png');
        pdf.addImage(imgData, 'PNG', 0, 0, 210, 297);
        if (i < sections.length - 1) {
          pdf.addPage();
        }
      }
      pdf.save('long-content.pdf');
    }
  }
}
</script>
<style lang="">

</style>